package com.itsm.utils;

import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class ImageUploadUtils {
    //图片上传，支持多张图片
    public static List<String> upload(List<MultipartFile> files, String path) throws IOException {
        List<String> msgs = new ArrayList<>();
        if (files.size() < 1) {
            msgs.add("file_empty");
            return msgs;
        }
        for (MultipartFile file : files) {
            String filename = file.getOriginalFilename();
            assert filename != null;
            String type = filename.contains(".") ? filename.substring(filename.lastIndexOf(".")) : null;
            //以uid重新命名避免重复
            //拼接文件路径，方便前端接收
            String filepath = path + UUID.randomUUID() + type;
            File filesPath = new File(path);
            if (!filesPath.exists()) {
                filesPath.mkdir();
            }
            BufferedOutputStream out = null;
            try {
                //输入图片字节流
                out = new BufferedOutputStream(new FileOutputStream(new File(filepath)));
                out.write(file.getBytes());
                msgs.add(filepath);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if(out != null){
                    out.flush();
                    out.close();
                }
            }
        }
        return msgs;
    }

    //文件删除
    public static boolean deleteFiles(String filePath){
        boolean flag = false;
        //根据路径创建文件对象
        File file = new File(filePath);
        //路径是个文件且不为空时删除文件
        if(file.isFile() && file.exists()){
            flag = file.delete();
        }
        //删除失败时，返回false
        return flag;
    }

}
